package com.gz.aop;

import com.gz.dto.BaseReq;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class TokenInjectionAspect {

    @Around("execution(* com.gz.controller..*(..)) && args(req, ..)")
    public Object injectToken(ProceedingJoinPoint joinPoint, BaseReq req) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            String token = request.getHeader("Authorization");
            if (token != null && !token.isEmpty()) {
                if (token.startsWith("Bearer ")) {
                    token = token.substring(7);
                }
                String[] split = token.split("-");
                if(split.length>1){
                    req.setRId(Integer.parseInt(split[0]));
                    req.setUId(Integer.parseInt(split[1]));
//                    req.setToken(split[0]);
                }
//                req.setToken(token);
            }
        }
        return joinPoint.proceed(); // 继续执行被拦截的方法
    }
}